package com.hhit.collaborative_learning.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import com.hhit.collaborative_learning.dao.CoopTalkDao;
import com.mysql.jdbc.StringUtils;

public class CoopTalkDaoImpl implements CoopTalkDao {

	@Override
	public ResultSet query(Connection con, int start, int end, String find,
			String order, String sort) {
		// TODO Auto-generated method stub
		String sql="SELECT ct.*,u.userNickName,u.userIcon FROM collaborative_learning.coop_topic as ct left join collaborative_learning.user as u on u.userId=ct.Creator ";
		if (!StringUtils.isNullOrEmpty(find)) {
			sql += " where " + find+ " ";
		}
		if (!StringUtils.isNullOrEmpty(sort)) {
			sql += " order by " + sort + " ";
			if (!StringUtils.isNullOrEmpty(order)) {
				sql += " " + order;
			}
		}
		if (end != 0 && start < end) {
			sql += " limit " + start + "," + end;
		}
		PreparedStatement prs;
		try {
			prs = con.prepareStatement(sql);
			System.out.println("请求：" + sql);
			return prs.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("非法请求：" + sql);
			return null;
		}
	}

	@Override
	public int insert(Connection con, String title, String body, String userid,
			String projid) {
		// TODO Auto-generated method stub
		String sql="INSERT INTO `collaborative_learning`.`coop_topic`(`Title`,`Body`,`Creator`,`CreatedOn`,`Coopp_id`,`State`)VALUES(?,?,?,?,?,?)";
		try {
			PreparedStatement prs = con.prepareStatement(sql);
			prs.setString(1, title);
			prs.setString(2, body);
			prs.setInt(3, Integer.valueOf(userid));
			prs.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
			prs.setInt(5,  Integer.valueOf(projid));
			prs.setString(6, "进行");
			return prs.executeUpdate();
		} catch (SQLException ex) {
			ex.printStackTrace();
			return 0;
		} 
	}

	@Override
	public int update(Connection con, String find, String state) {
		// TODO Auto-generated method stub
		String sql="UPDATE `collaborative_learning`.`coop_topic` SET `State` = '"+state+"'  WHERE "+find;
		try {
			PreparedStatement prs = con.prepareStatement(sql);
			return prs.executeUpdate();
		} catch (SQLException ex) {
			ex.printStackTrace();
			System.out.println("非法sql语句  "+sql);
			return 0;
		} 
	}

	@Override
	public int delete(Connection con, String find) {
		// TODO Auto-generated method stub
		String sql="DELETE FROM `collaborative_learning`.`coop_topic` WHERE "+find;
		try {
			PreparedStatement prs = con.prepareStatement(sql);
			return prs.executeUpdate();
		} catch (SQLException ex) {
			ex.printStackTrace();
			System.out.println("非法sql语句  "+sql);
			return 0;
		}
	}

}
